

package yf.mall.service.impl.app;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Objects;
import com.yf.service.impl.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yf.mall.dao.DyAccountAuthDao;
import yf.mall.entity.DyAccountAuthEntity;
import yf.mall.entity.DyAccountAuthEntityExample;
import yf.mall.entity.KolOrderEntity;
import yf.mall.entity.custom.PageQuery;
import yf.mall.mapper.DyAccountAuthExtMapper;
import yf.mall.service.app.DyAccountAuthService;
import yf.mall.service.app.KolOrderService;
import yf.mall.utils.MapperUtils;
import yf.mall.vo.DyAccountAuthVo;
import yf.mall.vo.down.DyAccountAuthDown;
import yf.mall.vo.up.DyAccountAuthUp;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 账户记录Service实现类
 *
 *
 *
 * @date Tue Jul 18 14:30:26 CST 2023
 */
@Slf4j
@Service
public class DyAccountAuthServiceImpl extends BaseServiceImpl<DyAccountAuthEntity> implements DyAccountAuthService {

    @Resource
    private DyAccountAuthDao dao;

    @Resource
    private DyAccountAuthExtMapper dyAccountAuthExtMapper;

    @Autowired
    public void setDao(DyAccountAuthDao dao) {
        this.dao = dao;
        super.setBaseDao(dao);
    }


    @Override
    public List<DyAccountAuthVo> findVo(DyAccountAuthVo vo) {
        return dao.findVo(vo);
    }

    @Override
    public DyAccountAuthVo getVo(Long id) {
        return dao.getVo(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveVo(DyAccountAuthVo vo) {
        return dao.save(vo.getEntity());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateVo(DyAccountAuthVo vo) {
        return dao.update(vo.getEntity());
    }


    @Override
    public void downLoad(HttpServletResponse response, List<DyAccountAuthVo> list) {
        try {
            List<DyAccountAuthDown> datas = list.stream().map(item -> new DyAccountAuthDown(item)).collect(Collectors.toList());
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), DyAccountAuthDown.class).sheet("模板").doWrite(datas);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Override
    public void upload(InputStream file) {
        EasyExcel.read(file, DyAccountAuthUp.class, new UploadDataListener()).sheet().doRead();
    }

    class UploadDataListener extends AnalysisEventListener<DyAccountAuthUp> {


        @Override
        @Transactional(rollbackFor = Exception.class)
        public void invoke(DyAccountAuthUp upVo, AnalysisContext analysisContext) {
            saveVo(upVo.toVo());
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        }

    }


    /**
     * 内部方法
     **/

    @Override
    public boolean createAccountAuth(DyAccountAuthEntity authEntity) {
        Long userId = authEntity.getUserId();
        if (authEntity == null || userId == null) {
            log.error("保存授权token信息失败，参数一次，authEntity={}，userId={}", authEntity, userId);
            return false;
        }
        List<DyAccountAuthEntity> allAuthByUser = this.getAllAuthByUser(userId);
        DyAccountAuthEntity dbAccountAuthEntity = allAuthByUser.stream().filter(auth -> Objects.equal(auth.getOpenId(), authEntity.getOpenId())).findFirst().orElse(null);
        if (dbAccountAuthEntity != null) {
            // 同一用户绑定同一openId信息时，只执行更新逻辑
            authEntity.setId(dbAccountAuthEntity.getId());
            authEntity.setRemark("更新token信息");
            dyAccountAuthExtMapper.updateByPrimaryKeySelective(authEntity);
        } else {
            authEntity.setRemark("创建token信息");
            dyAccountAuthExtMapper.insertSelective(authEntity);
        }
        allAuthByUser.stream().forEach(auth -> {
            if (Objects.equal(auth.getOpenId(), authEntity.getOpenId()) || auth.getMaster() != 1) {
                return;
            }
            auth.setMaster(0);
            dao.update(auth);
        });
        return true;
    }

    @Override
    public DyAccountAuthEntity getMasterAuthByUserId(Long userId) {
        DyAccountAuthEntity result = dao.findByUserIdAndMaster(userId, 1);
        return result;
    }

    @Override
    public List<DyAccountAuthEntity> getAllAuthByUser(Long userId) {
        if(userId == null){
            return Collections.emptyList();
        }
        DyAccountAuthEntity query = new DyAccountAuthEntity();
        query.setUserId(userId);
        return dao.find(query);
    }

    @Override
    public List<DyAccountAuthEntity> getAuthByOpenIds(List<String> openIds) {
        DyAccountAuthEntityExample example = new DyAccountAuthEntityExample();
        example.createCriteria().andOpenIdIn(openIds);
        return dyAccountAuthExtMapper.selectByExample(example);
    }

    @Override
    public DyAccountAuthEntity getDefaultToken() {
        DyAccountAuthEntityExample example = new DyAccountAuthEntityExample();
        DyAccountAuthEntityExample.Criteria criteria = example.createCriteria();
        MapperUtils.addCriterion(criteria, "auth_time <= NOW() AND DATE_ADD(auth_time, INTERVAL expires_in SECOND) > NOW()");
        example.setLimit(1);
        List<DyAccountAuthEntity> dyAccountAuthEntities = dyAccountAuthExtMapper.selectByExample(example);
        return dyAccountAuthEntities.stream().findFirst().orElse(null);
    }

    @Override
    public PageInfo<DyAccountAuthEntity> findUser(DyAccountAuthEntityExample example, PageQuery page) {
        PageHelper.startPage(page.getPageNumber(), page.getPageSize());
        List<DyAccountAuthEntity> entityList = dyAccountAuthExtMapper.selectByExample(example);
        return new PageInfo(entityList);
    }

    @Override
    public DyAccountAuthEntity getAuthByOpenId(String openId) {
        DyAccountAuthEntityExample example = new DyAccountAuthEntityExample();
        example.createCriteria().andOpenIdEqualTo(openId);
        return dyAccountAuthExtMapper.selectByExample(example).stream().findFirst().orElse(null);
    }

    @Override
    public boolean updateAuthToken(DyAccountAuthEntity authEntity) {
        DyAccountAuthEntityExample example = new DyAccountAuthEntityExample();
        example.createCriteria().andUserIdEqualTo(authEntity.getUserId()).andOpenIdEqualTo(authEntity.getOpenId());
        return dyAccountAuthExtMapper.updateByExampleSelective(authEntity,example) > 0;
    }

    @Override
    public DyAccountAuthEntity getAuthByUserAndDisplayId(Long userId, String displayId) {
        if(userId == null || displayId == null){
            return null;
        }
        DyAccountAuthEntityExample example = new DyAccountAuthEntityExample();
        example.createCriteria().andUserIdEqualTo(userId).andUidEqualTo(displayId);
        return dyAccountAuthExtMapper.selectByExample(example).stream().findFirst().orElse(null);
    }


    /**外部方法实现**/

}
